package pers.hl.module_main.admin.user

import android.content.Intent
import android.os.Bundle
import android.widget.TextView
import androidx.lifecycle.Observer
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import pers.hl.common.base.BaseVBVMActivity
import pers.hl.lib_global.model.bean.User
import pers.hl.module_main.CommonEditActivity
import pers.hl.module_main.R
import pers.hl.module_main.common.BaseLibQuickAdapter
import pers.hl.module_main.common.PageHelper
import pers.hl.module_main.common.SwipeMenuHelper
import pers.hl.module_main.databinding.ActivityUserManageBinding

class UserManageActivity : BaseVBVMActivity<ActivityUserManageBinding, UserManageViewModel>() {

    lateinit var userAdapter : BaseLibQuickAdapter<User, BaseViewHolder>

    override fun initView(savedInstanceState: Bundle?) {
        initRv()
        mBinding.titleBar.apply {
            tvBarTitle.text = "用户管理"
            ivBarLeft.setOnClickListener {
                finish()
            }
        }
    }

    private fun initRv() {
        userAdapter = object : BaseLibQuickAdapter<User, BaseViewHolder>(R.layout.item_rv_book_tag) {
            override fun convert(holder: BaseViewHolder, item: User) {
                holder.getView<TextView>(R.id.tvTagName).text = item.account
            }
        }
        val menuCreator = SwipeMenuHelper.createDeleteItem(this)
        mBinding.rvTag.apply {
            setSwipeMenuCreator(menuCreator)
            setOnItemMenuClickListener { menuBridge, adapterPosition ->
                // 任何操作必须先关闭菜单，否则可能出现Item菜单打开状态错乱。
                menuBridge.closeMenu()
                val deleteItem = userAdapter.getItem(adapterPosition)
                val userId = deleteItem.userId
                mViewModel.deleteUser(userId).observe(this@UserManageActivity, Observer {
                    getAll()
                })
            }
            adapter = userAdapter
        }
        userAdapter.setOnItemClickListener(OnItemClickListener { adapter, view, position ->
            val data = adapter.getItem(position) as User
            editUser(data)
        })
    }

    private fun editUser(data: User) {
        PageHelper.startUserHomePage(mContext, data.userId, true)
    }

    override fun initData(savedInstanceState: Bundle?) {
        getAll()
    }

    private fun getAll() {
        mViewModel.getAllUsers().observe(this, Observer {
            userAdapter.setList(it)
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == CommonEditActivity.RC_USER_MANAGE && resultCode == RESULT_OK) {
            getAll()
        }
    }

}